import { System, sp } from "cc";

export default class JNFrameSkeletonSystem extends System {

    /**
     * @en
     * The ID flag of the system.
     * @zh
     * 此系统的 ID 标记。
     */
    static readonly ID = 'JNFrameSkeletonSystem';

    private static _instance: JNFrameSkeletonSystem;

    private constructor () {
        super();
    }

    /**
     * @en
     * Gets the instance of the Spine Skeleton system.
     * @zh
     * 获取 Spine 骨骼系统的单例。
     */
    public static getInstance () {
        if (!JNFrameSkeletonSystem._instance) {
            console.log("JNSyncFrame 创建SpineSystem");
            JNFrameSkeletonSystem._instance = new JNFrameSkeletonSystem();
        }
        return JNFrameSkeletonSystem._instance;
    }

    /**
     * 销毁
     */
    public static deleteInstance(){
        console.log("JNSyncFrame 销毁 SpineSystem");
        JNFrameSkeletonSystem._instance = new JNFrameSkeletonSystem();
    }

    private _skeletons = new Set<sp.Skeleton>();

    public add (skeleton: sp.Skeleton | null) {
        if (!skeleton) return;
        if (!this._skeletons.has(skeleton)) {
            this._skeletons.add(skeleton);
        }
    }

    public remove (skeleton: sp.Skeleton | null) {
        if (!skeleton) return;
        if (this._skeletons.has(skeleton)) {
            this._skeletons.delete(skeleton);
        }
    }

    onUpdate(dt: number){
        this.postUpdate(dt);
    }

    postUpdate (dt: number) {
        if (!this._skeletons) {
            return;
        }
        this._skeletons.forEach((skeleton) => {
            skeleton.updateAnimation(dt);
            skeleton["syncAttachedNode"]();
        });
    }

    public prepareRenderData () {
        if (!this._skeletons) {
            return;
        }
        this._skeletons.forEach((skeleton) => {
            skeleton.markForUpdateRenderData();
        });
    }

}

